package com.lorenzogao.pley.common.rx

import android.content.Context
import android.widget.Toast
import com.lorenzogao.pley.common.exception.ApiException
import com.lorenzogao.pley.common.exception.BaseException
import com.lorenzogao.pley.common.exception.ErrorMessageFactory
import retrofit2.HttpException

import java.net.SocketException
import java.net.SocketTimeoutException

/**
 * 作者：Lorenzo Gao
 * Date: 2018/1/2
 * Time: 10:55
 * 邮箱：2508719070@qq.com
 * Description:
 */
class RxErrorHandler(context: Context) {

    var mContext: Context = context

    fun handlerError(e: Throwable): BaseException {
        var excption = BaseException()
        when (e) {
            is ApiException -> {
                excption.code = (e as ApiException).code
            }
            is SocketException -> {
                excption.code = BaseException.SCOKET_ERROR
            }
            is HttpException -> {
                excption.code = BaseException.HTTP_ERROR
            }
            is SocketTimeoutException -> {
                excption.code = BaseException.SCOKET_ERROR
            }
            else -> {
                if (excption.code == 0) {
                    excption.code = BaseException.ERROR_PARAMS
                } else {
                    excption.code = BaseException.UNKNOWN_ERROR
                }
            }
        }
        excption.dispatymessage = ErrorMessageFactory.create(mContext, excption.code)

        return excption
    }


    fun showErrorMessage(e: BaseException) {
        Toast.makeText(mContext, e.dispatymessage, Toast.LENGTH_SHORT).show()
    }
}